<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { formatTime } from '@/utils/usertools'
import { usePlayerStore } from '@/stores/player'
import type { Music } from '@/stores/player'
import PlayList from './PlayList.vue'
import { getMusicSource, addToRecentPlay, getPlaylist, addToPlaylist } from '@/api/music'
import AudioEffect from './AudioEffect.vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const audio = ref<HTMLAudioElement | null>(null)
const currentTime = ref('00:00')
const duration = ref('00:00')
const progress = ref(0)
const isPlaying = computed(() => playerStore.isPlaying)
const volume = ref(50)
const isMuted = ref(false)
const isProgressDragging = ref(false)
const isVolumeDragging = ref(false)
const showPlaylist = ref(false)
const playMode = ref<'sequence' | 'random' | 'single'>('sequence')
const showAudioEffect = ref(false)

const playerStore = usePlayerStore()
const userStore = useUserStore()

// 进度条控制
const setProgress = (e: MouseEvent) => {
  if (!playerStore.audio) return
  const slider = e.currentTarget as HTMLElement
  const rect = slider.getBoundingClientRect()
  const percentage = (e.clientX - rect.left) / rect.width
  const newTime = percentage * playerStore.audio.duration
  playerStore.setCurrentTime(newTime)
}

const startDrag = (e: MouseEvent) => {
  isProgressDragging.value = true
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

const handleDrag = (e: MouseEvent) => {
  if (!isProgressDragging.value || !playerStore.audio) return
  const slider = document.querySelector('.slider') as HTMLElement
  if (!slider) return
  
  const rect = slider.getBoundingClientRect()
  let percentage = (e.clientX - rect.left) / rect.width
  if (!isFinite(percentage)) return
  percentage = Math.max(0, Math.min(1, percentage))
  
  progress.value = percentage * 100
  const newTime = percentage * (playerStore.audio.duration || 0)
  if (isFinite(newTime)) {
    playerStore.setCurrentTime(newTime)
  }
}

const stopDrag = () => {
  isProgressDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 音量控制
const setVolume = (e: MouseEvent) => {
  if (!playerStore.audio) return
  const slider = e.currentTarget as HTMLElement
  const rect = slider.getBoundingClientRect()
  let percentage = (e.clientX - rect.left) / rect.width
  percentage = Math.max(0, Math.min(1, percentage))
  volume.value = percentage * 100
  playerStore.setVolume(percentage)
}

const startVolumeDrag = (e: MouseEvent) => {
  isVolumeDragging.value = true
  document.addEventListener('mousemove', handleVolumeDrag)
  document.addEventListener('mouseup', stopVolumeDrag)
}

const handleVolumeDrag = (e: MouseEvent) => {
  if (!isVolumeDragging.value || !playerStore.audio) return
  const slider = document.querySelector('.volume-slider') as HTMLElement
  if (!slider) return
  
  const rect = slider.getBoundingClientRect()
  let percentage = (e.clientX - rect.left) / rect.width
  percentage = Math.max(0, Math.min(1, percentage))
  
  volume.value = percentage * 100
  playerStore.setVolume(percentage)
}

const stopVolumeDrag = () => {
  isVolumeDragging.value = false
  document.removeEventListener('mousemove', handleVolumeDrag)
  document.removeEventListener('mouseup', stopVolumeDrag)
}

const togglePlay = async () => {
  if (!playerStore.audio) return
  
  try {
    if (playerStore.isPlaying) {
      await playerStore.audio.pause()
      playerStore.isPlaying = false
    } else {
      if (!playerStore.audio.src && playerStore.currentMusic.id) {
        await playerStore.playMusic(playerStore.currentMusic)
      } else {
        await playerStore.audio.play()
        await addToRecentPlay(playerStore.currentMusic.id)
        playerStore.isPlaying = true
      }
    }
  } catch (error) {
    console.error('播放控制失败:', error)
  }
}

const toggleMute = () => {
  if (!playerStore.audio) return
  isMuted.value = !isMuted.value
  const newVolume = isMuted.value ? 0 : volume.value / 100
  playerStore.setVolume(newVolume)
}

// 更新进度
const updateProgress = () => {
  if (!playerStore.audio || isProgressDragging.value) return
  
  // 如果没有正在播放的音乐，重置进度和时间显示
  if (!playerStore.currentMusic.id) {
    currentTime.value = '00:00'
    duration.value = '00:00'
    progress.value = 0
    return
  }
  
  currentTime.value = formatTime(playerStore.audio.currentTime)
  progress.value = (playerStore.audio.currentTime / playerStore.audio.duration) * 100
}

const togglePlaylist = () => {
  if (!userStore.isLoggedIn) {
    ElMessage({
      message: '该功能需要登录',
      type: 'warning',
      duration: 2000
    })
    return
  }
  
  if (playerStore.playlist.length > 0) {
    showPlaylist.value = !showPlaylist.value
  }
}

// 播放模式切换
const togglePlayMode =() => {
  if (playMode.value === 'sequence') {
    playMode.value = 'random'
  } else if (playMode.value === 'random') {
    playMode.value = 'single'
  } else {
    playMode.value = 'sequence'
  }
}

const playNext = () => {
  const playlist = playerStore.playlist
  if (playlist.length <= 1) return
  
  switch (playMode.value) {
    case 'random': {
      let randomIndex
      do {
        randomIndex = Math.floor(Math.random() * playlist.length)
      } while (randomIndex === playlist.findIndex(song => song.id === playerStore.currentMusic.id))
      playerStore.playMusic(playlist[randomIndex])
      break
    }
    case 'sequence': {
      const currentIndex = playlist.findIndex(song => song.id === playerStore.currentMusic.id)
      const nextIndex = currentIndex === playlist.length - 1 ? 0 : currentIndex + 1
      playerStore.playMusic(playlist[nextIndex])
      break
    }
    case 'single': {
      if (playerStore.audio) {
        playerStore.audio.currentTime = 0
        playerStore.audio.play()
      }
      break
    }
  }
}

const playPrev = () => {
  const playlist = playerStore.playlist
  if (playlist.length <= 1) return
  
  switch (playMode.value) {
    case 'random': {
      let randomIndex
      do {
        randomIndex = Math.floor(Math.random() * playlist.length)
      } while (randomIndex === playlist.findIndex(song => song.id === playerStore.currentMusic.id))
      playerStore.playMusic(playlist[randomIndex])
      break
    }
    case 'sequence': {
      const currentIndex = playlist.findIndex(song => song.id === playerStore.currentMusic.id)
      const prevIndex = currentIndex === 0 ? playlist.length - 1 : currentIndex - 1
      playerStore.playMusic(playlist[prevIndex])
      break
    }
    case 'single': {
      if (playerStore.audio) {
        playerStore.audio.currentTime = 0
        playerStore.audio.play()
      }
      break
    }
  }
}

const handleEnded = () => {
  switch (playMode.value) {
    case 'single': {
      if (playerStore.audio) {
        playerStore.audio.currentTime = 0
        playerStore.audio.play()
        playerStore.isPlaying = true
      }
      break
    }
    default: {
      playNext()
    }
  }
}

// 添加跳转到详情页的函数
const goToDetail = () => {
  if (playerStore.currentMusic.id) {
    router.push('/detail')
  }
}

onMounted(async () => {
  playerStore.initAudio()
  if(playerStore.audio) {
    playerStore.audio.addEventListener('timeupdate', updateProgress)
    playerStore.audio.addEventListener('loadedmetadata', () => {
      if (playerStore.audio && playerStore.currentMusic.id) {
        duration.value = formatTime(playerStore.audio.duration)
      } else {
        duration.value = '00:00'
      }
    })
    
    playerStore.audio.addEventListener('ended', handleEnded)
    
    playerStore.audio.addEventListener('error', (e) => {
      console.error('音频加载错误:', e)
    })
    playerStore.setVolume(volume.value / 100)
  }

  try {
    const playlist = await getPlaylist()
    playerStore.setPlaylist(playlist)
  } catch (error) {
    console.error('获取播放列表失败:', error)
  }
})

onUnmounted(() => {
  if (playerStore.audio) {
    playerStore.audio.removeEventListener('timeupdate', updateProgress)
    playerStore.audio.removeEventListener('loadedmetadata', () => {})
    playerStore.audio.removeEventListener('ended', handleEnded)
  }
})
</script>

<template>
  <div class="play-bar">
    <div class="play-container">
      <!-- 歌曲信息 -->
      <div class="song-info" :class="{ empty: !playerStore.currentMusic.id }">
        <div class="song-cover" @click="goToDetail">
          <div v-if="!playerStore.currentMusic.id" class="default-cover">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12,3V12.26C11.5,12.09 11,12 10.5,12C8.56,12 7,13.56 7,15.5C7,17.44 8.56,19 10.5,19C12.44,19 14,17.44 14,15.5V6H18V3H12Z" />
            </svg>
          </div>
          <img 
            v-else
            :src="playerStore.currentMusic.cover || '/src/assets/default-cover.png'" 
            :alt="playerStore.currentMusic.title || '暂无歌曲'"
          >
          <div class="cover-mask" v-if="playerStore.currentMusic.id">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z"/>
            </svg>
          </div>
        </div>
        <div class="song-detail">
          <div class="song-name">{{ playerStore.currentMusic.title || '暂无播放' }}</div>
          <div class="artist-name">{{ playerStore.currentMusic.artist || '点击播放按钮开始' }}</div>
        </div>
      </div>

      <!-- 中间：播放控制 -->
      <div class="play-control">
        <div class="control-buttons">
          <button class="prev" @click="playPrev" :disabled="!playerStore.currentMusic.id">
            <i class="icon-prev">⏮</i>
          </button>
          <button 
            class="play-pause" 
            @click="togglePlay"
            :disabled="!playerStore.currentMusic.id"
            :class="{ disabled: !playerStore.currentMusic.id }"
          >
            <i class="icon-play" v-if="!isPlaying">▶</i>
            <i class="icon-pause" v-else>⏸</i>
          </button>
          <button class="next" @click="playNext" :disabled="!playerStore.currentMusic.id">
            <i class="icon-next">⏭</i>
          </button>
        </div>
        <div class="progress-bar">
          <span class="time">{{ currentTime }}</span>
          <div 
            class="slider" 
            @click="setProgress"
            :class="{ disabled: !playerStore.currentMusic.id }"
          >
            <div class="slider-bar" :style="{ width: progress + '%' }"></div>
            <div 
              class="slider-dot" 
              :style="{ left: progress + '%' }"
              @mousedown="startDrag"
              v-if="playerStore.currentMusic.id"
            ></div>
          </div>
          <span class="time">{{ duration }}</span>
        </div>
      </div>

      <!-- 右侧：音量控制等 -->
      <div class="play-actions">
        <!-- 播放模式 -->
        <button class="mode" 
                @click="togglePlayMode" 
                :title="playMode === 'sequence' ? '顺序播放' : playMode === 'random' ? '随机播放' : '单曲循环'">
          <!-- 顺序播放图标 -->
          <svg v-if="playMode === 'sequence'" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M17 17H7V14L3 18L7 22V19H19V13H17M7 7H17V10L21 6L17 2V5H5V11H7V7Z"/>
          </svg>
          <!-- 随机播放图标 -->
          <svg v-else-if="playMode === 'random'" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M17,3L22.25,7.5L17,12L22.25,16.5L17,21V18H14.26L11.44,15.18L13.56,13.06L15.5,15H17V12L17,9H15.5L6.5,18H2V15H5.26L14.26,6H17V3M2,6H6.5L9.32,8.82L7.2,10.94L5.26,9H2V6Z"/>
          </svg>
          <!-- 单曲循环图标 -->
          <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M17 17H7V14L3 18L7 22V19H19V13H17M7 7H17V10L21 6L17 2V5H5V11H7V7M13 13V8H11V13H8L12 17L16 13H13Z"/>
          </svg>
        </button>

        <!-- 音控制 -->
        <div class="volume-control">
          <button class="volume" @click="toggleMute" title="音量">
            <svg v-if="!isMuted" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M14,3.23V5.29C16.89,6.15 19,8.83 19,12C19,15.17 16.89,17.84 14,18.7V20.77C18,19.86 21,16.28 21,12C21,7.72 18,4.14 14,3.23M16.5,12C16.5,10.23 15.5,8.71 14,7.97V16C15.5,15.29 16.5,13.76 16.5,12M3,9V15H7L12,20V4L7,9H3Z"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12,4L9.91,6.09L12,8.18M4.27,3L3,4.27L7.73,9H3V15H7L12,20V13.27L16.25,17.53C15.58,18.04 14.83,18.46 14,18.7V20.77C15.38,20.45 16.63,19.82 17.68,18.96L19.73,21L21,19.73L12,10.73M19,12C19,12.94 18.8,13.82 18.46,14.64L19.97,16.15C20.62,14.91 21,13.5 21,12C21,7.72 18,4.14 14,3.23V5.29C16.89,6.15 19,8.83 19,12M16.5,12C16.5,10.23 15.5,8.71 14,7.97V10.18L16.45,12.63C16.5,12.43 16.5,12.21 16.5,12Z"/>
            </svg>
          </button>
          <div class="volume-slider" @click="setVolume">
            <div class="slider-bar" :style="{ width: volume + '%' }"></div>
            <div 
              class="slider-dot" 
              :style="{ left: volume + '%' }"
              @mousedown="startVolumeDrag"
            ></div>
          </div>
        </div>

        <!-- 音效按钮 -->
        <button 
          class="effect" 
          title="音效" 
          @click="showAudioEffect = !showAudioEffect"
          :disabled="!playerStore.currentMusic.id"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12,3V12.26C11.5,12.09 11,12 10.5,12C8.56,12 7,13.56 7,15.5C7,17.44 8.56,19 10.5,19C12.44,19 14,17.44 14,15.5V6H18V3H12Z" />
          </svg>
        </button>

        <!-- 播放列表 -->
        <button 
          class="playlist" 
          title="播放列表" 
          @click="togglePlaylist"
          :disabled="!playerStore.playlist.length"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M3,13H5V11H3M3,17H5V15H3M3,9H5V7H3M7,13H21V11H7M7,17H21V15H7M7,7V9H21V7M3,13H5V11H3M3,17H5V15H3M3,9H5V7H3M7,13H21V11H7M7,17H21V15H7M7,7V9H21V7"/>
          </svg>
        </button>
      </div>
    </div>
    
    <!-- 添加 PlayList 组件 -->
    <Transition name="slide">
      <PlayList v-if="showPlaylist" @close="showPlaylist = false" />
    </Transition>

    <!-- 添加 AudioEffect 组件 -->
    <Transition name="slide">
      <AudioEffect v-if="showAudioEffect" @close="showAudioEffect = false" />
    </Transition>
  </div>
</template>

<style scoped lang="scss">
.play-bar {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translateX(-50%);
  width: 90%;
  max-width: 1200px;
  height: 80px;
  background: color-mix(in srgb, var(--theme-color) 85%, black);
  border-radius: 12px;
  box-shadow: 
    0 10px 30px rgba(0, 0, 0, 0.25),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  z-index: 100;

  .play-container {
    max-width: 100%;
    height: 100%;
    margin: 0 auto;
    padding: 0 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // 左侧歌曲信息
    .song-info {
      display: flex;
      align-items: center;
      gap: 15px;
      width: 280px;

      .song-cover {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        overflow: hidden;
        position: relative;
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        background: rgba(255, 255, 255, 0.05);
        
        .default-cover {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: rgba(255, 255, 255, 0.3);
          background: linear-gradient(
            145deg,
            rgba(255, 255, 255, 0.05),
            rgba(255, 255, 255, 0.02)
          );
          
          svg {
            opacity: 0.5;
            transform: scale(1.2);
          }
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .cover-mask {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            145deg,
            color-mix(in srgb, var(--theme-color) 80%, transparent),
            color-mix(in srgb, var(--theme-color) 60%, transparent)
          );
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          svg {
            transform: translateY(10px);
            transition: transform 0.3s ease;
            color: white;
          }
        }

        &:hover {
          .cover-mask {
            opacity: 1;

            svg {
              transform: translateY(0);
            }
          }
        }
      }

      .song-detail {
        .song-name {
          color: #ffffff;
          font-size: 14px;
          margin-bottom: 4px;
          font-weight: 500;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        .artist-name {
          color: var(--secondary-color);
          font-size: 12px;
          opacity: 0.9;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
      }

      &.empty {
        opacity: 0.8;
        cursor: default;
        
        .song-cover {
          filter: grayscale(1);
        }
      }
    }

    // 中间播放控制
    .play-control {
      flex: 1;
      max-width: 600px;
      padding: 0 20px;

      .control-buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 20px;
        margin-bottom: 8px;

        button {
          background: none;
          border: none;
          color: rgba(255, 255, 255, 0.8);
          cursor: pointer;
          transition: all 0.3s;
          padding: 8px;
          border-radius: 50%;

          &:hover {
            color: #ffffff;
            background: rgba(255, 255, 255, 0.1);
            transform: translateY(-2px);
          }

          &:active {
            transform: translateY(-1px);
          }

          &.play-pause {
            width: 35px;
            height: 35px;
            background: #ffffff;
            color: var(--theme-color);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            
            &:hover {
              transform: translateY(-2px) scale(1.05);
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
              background: #ffffff;
            }
            
            &:active {
              transform: translateY(-1px) scale(1.02);
            }

            &.disabled {
              background: rgba(255, 255, 255, 0.3);
              color: rgba(255, 255, 255, 0.5);
              box-shadow: none;
            }
          }
        }
      }

      .progress-bar {
        display: flex;
        align-items: center;
        gap: 10px;

        .time {
          color: rgba(255, 255, 255, 0.95) !important;
          font-size: 12px;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .slider {
          flex: 1;
          height: 4px;
          background: rgba(255, 255, 255, 0.2) !important;
          border-radius: 2px;
          position: relative;
          cursor: default;

          .slider-bar {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            background: #ffffff !important;
            border-radius: 2px;
          }

          .slider-dot {
            position: absolute;
            top: 50%;
            width: 14px;
            height: 14px;
            background: #ffffff;
            border: 2px solid var(--theme-color);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: transform 0.2s;
            z-index: 1;
            box-shadow: 0 2px 8px var(--theme-shadow);
            
            &:hover, &:active {
              background: #ffffff;
              transform: translate(-50%, -50%) scale(1.2);
              box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.2);
            }
          }
        }
      }
    }

    // 右侧控制
    .play-actions {
      display: flex;
      align-items: center;
      gap: 20px;
      width: 280px;
      justify-content: flex-end;

      button {
        background: none;
        border: none;
        color: rgba(255, 255, 255, 0.95);
        cursor: pointer;
        transition: all 0.3s;
        padding: 8px;
        border-radius: 50%;

        &:hover {
          color: #ffffff;
          background: rgba(255, 255, 255, 0.15);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(-1px);
        }

        &:disabled {
          opacity: 0.5;
          background: none;
          
          &:hover {
            transform: none;
          }
        }
      }

      .volume-control {
        display: flex;
        align-items: center;
        gap: 8px;

        .volume-slider {
          width: 80px;
          height: 4px;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 2px;
          position: relative;
          cursor: default;

          .slider-bar {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            background: #ffffff !important;
            border-radius: 2px;
          }

          .slider-dot {
            position: absolute;
            top: 50%;
            width: 12px;
            height: 12px;
            background: #ffffff;
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: transform 0.2s;
            z-index: 1;
            box-shadow: 0 2px 8px var(--theme-shadow);
            
            &:hover, &:active {
              transform: translate(-50%, -50%) scale(1.2);
              box-shadow: 0 4px 12px color-mix(in srgb, var(--theme-color) 50%, transparent);
            }
          }

          &:hover {     
            .slider-dot {
              border-color: var(--hover-color);
            }
          }
        }
      }

      .effect {
        // 继承其他按钮的基本样式
        background: none;
        border: none;
        color: rgba(255, 255, 255, 0.95);
        cursor: pointer;
        transition: all 0.3s;
        padding: 8px;
        border-radius: 50%;

        &:hover {
          color: #ffffff;
          background: rgba(255, 255, 255, 0.15);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(-1px);
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
          
          &:hover {
            transform: none;
            background: none;
          }
        }
      }
    }
  }
}

// 添加过渡动画
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateY(30px);
  opacity: 0;
}

.mode {
  svg {
    transition: transform 0.3s ease;
  }
  
  &:hover svg {
    transform: scale(1.1);
  }
  
  &:active svg {
    transform: scale(0.95);
  }
}

// 优化按钮禁用状态
button {
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    
    &:hover {
      color: rgba(232, 245, 233, 0.5);
      transform: none;
    }
  }
}

.play-pause {
  &.disabled {
    background: color-mix(in srgb, var(--theme-color) 10%, transparent) !important;
  }
}
</style>
